//
//  EditUserInfoViewController.m
//  QuickCure1
//
//  Created by apple on 2016/11/2.
//  Copyright © 2016年 maoge. All rights reserved.
//

#import "EditUserInfoViewController.h"
#import "EditTopView.h"
#import "userInfoCell.h"
#import "EditUserInfoModel.h"
//城市模型头文件
#import "HomeProvinceModel.h"

@interface EditUserInfoViewController ()<UITableViewDelegate,UITableViewDataSource,UIPickerViewDelegate,UIPickerViewDataSource>

@property (nonatomic,strong)Users *userInfo;

@property (nonatomic,strong)NSArray *arrTab;

@property (nonatomic,strong)NSMutableArray *arrInfo;

@property (nonatomic,weak)UITableView *tableView;

@property (nonatomic,strong)NSIndexPath *indexPath;

@property (nonatomic,weak)UIView *editView;

@property (nonatomic,weak)UIPickerView *pickerView;
//存储读取省份城市的plist文件的model
@property (nonatomic,strong)NSArray<HomeProvinceModel *> *provinceArr;
//记录pickerView的值
@property (nonatomic,strong)NSMutableArray *arrM;
//记录选择的省份
@property (nonatomic,copy) NSString *province;
//记录选择的城市
@property (nonatomic,copy) NSString *city;
//记录选择的省份的下标
//@property (nonatomic,assign)NSInteger provinveRow;
//记录打开编辑View的时候省份的下标
@property (nonatomic,assign)NSInteger index;
//记录沙盒中存储的用户省份在数组中对应的model
@property (nonatomic,strong)HomeProvinceModel *model;
//提示用户省份城市不匹配的视图
@property (nonatomic,weak)UIView *promptView;


@end

static NSString *cellID = @"cellID";

@implementation EditUserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self setupUI];
}

#pragma mark
#pragma mark - 加载城市数据
- (void)loadData{
    self.arrM = @[@"0",@"0",@"0"].mutableCopy;
    
    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"province.plist" ofType:nil];
    NSArray *arr = [NSArray arrayWithContentsOfFile:filePath];
    NSMutableArray *arrM = [NSMutableArray array];
    for (NSDictionary *dict in arr) {
        HomeProvinceModel *model = [[HomeProvinceModel alloc]init];
        [model setValuesForKeysWithDictionary:dict];
        [arrM addObject:model];
    }
    self.provinceArr = arrM.copy;
}
#pragma mark
#pragma mark - 省份城市不匹配的提示框
- (UIView *)promptView{
    
    if (_promptView == nil) {
        
        UIView *promptView = [[UIView alloc]init];
        
        [self.view addSubview:promptView];
        
        promptView.layer.cornerRadius = 10;
        promptView.layer.masksToBounds = YES;
        promptView.backgroundColor = [UIColor lightGrayColor];
        promptView.alpha = 0;
        
        [promptView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(200, 80));
        }];
        
        UILabel *label = [[UILabel alloc]init];
        
        [promptView addSubview:label];
        
        label.text = @"省份城市不正确,请重新选择!";
        label.textColor = [UIColor redColor];
        label.numberOfLines = 0;
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(promptView);
            make.leading.equalTo(promptView).offset(20);
            make.trailing.equalTo(promptView).offset(-20);
        }];
        
        _promptView = promptView;
    }
    return _promptView;
}


#pragma mark
#pragma mark - 编辑视图
- (UIView *)editView{
    
    if (_editView == nil) {
        //创建编辑视图
        UIView *editView = [[UIView alloc]init];
        
        [self.view addSubview:editView];
        self.editView = editView;
        
        editView.backgroundColor =kMyColor;
        editView.alpha = 0;
        editView.layer.cornerRadius = 10;
        editView.layer.masksToBounds = YES;
        
        [editView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.view);
            make.width.equalTo(@300);
            make.height.equalTo(@300);
        }];
        
        
        UIPickerView *pickView = [[UIPickerView alloc]init];
        

        [editView addSubview:pickView];
        self.pickerView = pickView;
        pickView.dataSource = self;
        pickView.delegate = self;
        
        [pickView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(editView);
            make.centerX.equalTo(editView);
            make.size.mas_equalTo(CGSizeMake(260, 200));
        }];
        
        //确定按钮
        UIButton *buttonOK = [UIButton buttonWithType:UIButtonTypeCustom];
        [buttonOK setTitle:@"确定" forState:UIControlStateNormal];
        [buttonOK setBackgroundColor:[UIColor lightGrayColor]];
        [buttonOK setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [buttonOK setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [editView addSubview:buttonOK];
        [buttonOK mas_makeConstraints:^(MASConstraintMaker *make) {
            //            make.centerX.equalTo(editView);
            make.leading.equalTo(editView.mas_centerX).offset(20);
            make.bottom.equalTo(editView.mas_bottom).offset(-20);
            make.size.mas_equalTo(CGSizeMake(80, 30));
        }];
        [buttonOK addTarget:self action:@selector(clickbuttonOK:) forControlEvents:UIControlEventTouchUpInside];
        
        //取消按钮
        UIButton *buttonNo = [UIButton buttonWithType:UIButtonTypeCustom];
        [buttonNo setTitle:@"取消" forState:UIControlStateNormal];
        [buttonNo setBackgroundColor:[UIColor lightGrayColor]];
        [buttonNo setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [buttonNo setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [editView addSubview:buttonNo];
        
        [buttonNo mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.equalTo(editView.mas_centerX).offset(-20);
            make.bottom.equalTo(editView.mas_bottom).offset(-20);
            make.size.mas_equalTo(CGSizeMake(80, 30));
        }];
        [buttonNo addTarget:self action:@selector(clickButtonNo:) forControlEvents:UIControlEventTouchUpInside];

        _editView = editView;
    }
    
    return _editView;
}

#pragma mark
#pragma mark - pickView代理方法
//对应列行的数据
- (nullable NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (self.indexPath.row == 0 || self.indexPath.row == 1) {
        return @(row).description;
    }else if (self.indexPath.row == 2){
        return self.provinceArr[row].name;
    }
    HomeProvinceModel *model = self.provinceArr[self.index];
    return model.cities[row];
}

//列数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    NSLog(@"%zd",self.indexPath.row);
    if (self.indexPath.row == 2 || self.indexPath.row == 3) {
        return 1;
    }
    return 3;
}

//每列的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (self.indexPath.row == 2) {
        return self.provinceArr.count;
    }else if (self.indexPath.row == 3){
        
    }
    return 10;
}


//选中行的数据
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    
    

    if (self.indexPath.row == 0 || self.indexPath.row == 1) {
        
        self.arrM[component] = [NSString stringWithFormat:@"%zd",row];
//        NSLog(@"%@",self.arrM);
    }else if (self.indexPath.row == 2){
//        self.provinveRow = row;
        self.province = self.provinceArr[row].name;

    }else{
        
        NSInteger index = [self getProvinceIndex];
        HomeProvinceModel *model = self.provinceArr[index];
        self.city = model.cities[row];
    }
}

#pragma mark
#pragma mark - 编辑用户数据确定按钮点击方法
- (void)clickbuttonOK:(UIButton *)button{
    
    NSMutableString *strM = [NSMutableString string];
    for (NSString *str in self.arrM) {
        [strM appendString:str];
    }
    NSIndexPath *index = self.indexPath;
    NSInteger row = index.row;
    switch (row) {
        case 0:
            self.arrInfo[row] = strM;
            break;
        case 1:
            self.arrInfo[row] = strM;
            break;
        case 2:
            if (self.province) {
                self.arrInfo[row] = self.province;
            }
            break;
        case 3:
            if (self.city) {
                self.arrInfo[row] = self.city;
            }
            break;
        default:
            break;
    }
    [UIView animateWithDuration:1 animations:^{
        self.editView.alpha = 0;
    }completion:^(BOOL finished) {
        
        [self.tableView reloadData];
    }];

}

#pragma mark
#pragma mark - 取消按钮点击方法
- (void)clickButtonNo:(UIButton *)button{
    
    [UIView animateWithDuration:1 animations:^{
        self.editView.alpha = 0;
    }completion:^(BOOL finished) {
        NSLog(@"取消编辑");
    }];
    
}


#pragma mark
#pragma mark - 界面搭建
- (void)setupUI{
    self.title = @"个人信息修改";
#pragma mark - 反归档读取用户数据
    //使用单例对象反归档_______________________________________________
    [[UserManager sharedManager]getUserInfoFromCache];
    Users *us = [UserManager sharedManager].userInfo;
    
    self.userInfo = us;
    
#pragma mark - 读取沙盒中存储的假数据

    NSString *Path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *filePath = [Path stringByAppendingPathComponent:@"editUserInfo.plist"];
    EditUserInfoModel *editModel = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    
    NSArray *arr = @[editModel.height,editModel.weight,editModel.province_id,editModel.city_id];
    
    self.arrInfo = [[NSMutableArray alloc]initWithArray:arr];
    
    //属性赋值,记录cell左侧文字
    self.arrTab = @[@"身高",@"体重",@"省份",@"城市"];
    
    //加载XIB
    EditTopView *topView = [EditTopView topView];
    
    //顺传
    topView.userInfo = self.userInfo;
    
    [self.view addSubview:topView];
    
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(64);
        make.leading.trailing.equalTo(self.view);
        make.height.equalTo(@120);
    }];
    
#pragma mark - tableView
    UITableView *tableView = [[UITableView alloc]init];
    
    [self.view addSubview:tableView];
    
    self.tableView = tableView;
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView.mas_bottom);
        make.leading.trailing.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.rowHeight = 50;
    [tableView registerClass:[userInfoCell class] forCellReuseIdentifier:cellID];
    
#pragma mark - 保存按钮
    UIBarButtonItem *preserveButton = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(clickButtonPreserveUserInfo:)];
    [preserveButton setTintColor:[UIColor whiteColor]];
    //添加保存按钮
    self.navigationItem.rightBarButtonItem = preserveButton;
    
}

#pragma mark
#pragma mark - 保存按钮的监听方法
- (void)clickButtonPreserveUserInfo:(UIBarButtonItem *)button{
    //判断用户现在的省份很城市是否匹配,如果匹配就保存,不然不保存.
    BOOL isTrue = NO;
    NSInteger index = [self getProvinceIndex];
    HomeProvinceModel *model = self.provinceArr[index];
    for (NSString *str in model.cities) {
        if ([self.arrInfo[3] isEqualToString:str]) {
            isTrue = YES;
        }
    }
    if (isTrue) {
        
        EditUserInfoModel *editInfoModel = [[EditUserInfoModel alloc]init];
        editInfoModel.height = self.arrInfo[0];
        editInfoModel.weight = self.arrInfo[1];
        editInfoModel.province_id = self.arrInfo[2];
        editInfoModel.city_id = self.arrInfo[3];
        
        NSString *Path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        NSString *filePath = [Path stringByAppendingPathComponent:@"editUserInfo.plist"];
        
        [NSKeyedArchiver archiveRootObject:editInfoModel toFile:filePath];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    else{
        
        [UIView animateWithDuration:2 animations:^{
            self.promptView.alpha = 1;
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:1 animations:^{
                self.promptView.alpha = 0;
                [self.promptView removeFromSuperview];
            }];
        }];
    }
    
}

#pragma mark
#pragma mark - tableView的代理方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    userInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    
    cell.textLabel.text = self.arrTab[indexPath.row];
//    NSString *str = [NSString stringWithFormat:@"%zd",[self.arrInfo[indexPath.row] integerValue]];
    cell.detailTextLabel.text = self.arrInfo[indexPath.row];

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.indexPath = indexPath;
    [UIView animateWithDuration:1 animations:^{
#pragma mark - 刷新pickerView的内容
        [self.pickerView reloadAllComponents];
        self.editView.alpha = 0.7;
    }];
    if (indexPath.row == 0 || indexPath.row == 1) {
        
        NSString *str = self.arrInfo[indexPath.row];
        
        NSInteger Num = [str integerValue];
        
        NSInteger bai = Num / 100;
        
        NSInteger shi = Num % 100 / 10;
        
        NSInteger ge = Num % 10;
        
        [self.pickerView selectRow:bai inComponent:0 animated:NO];
        [self.pickerView selectRow:shi inComponent:1 animated:NO];
        [self.pickerView selectRow:ge inComponent:2 animated:NO];
    }else if (indexPath.row == 2){
        
        self.index = [self getProvinceIndex];

        [self.pickerView selectRow:self.index inComponent:0 animated:NO];
        
    }else{
        self.index = [self getProvinceIndex];
        NSInteger index = [self getCityIndex];
        [self.pickerView selectRow:index inComponent:0 animated:NO];
    }
    
}

#pragma mark
#pragma mark - 获取已经存储的省份对应的下标
- (NSInteger)getProvinceIndex{
    
    NSString *str = self.arrInfo[2];
    
    __block NSInteger index = 0;
    [self.provinceArr enumerateObjectsUsingBlock:^(HomeProvinceModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.name isEqualToString:str]) {
            self.model = obj;
            NSString *string = [NSString stringWithFormat:@"%lu",idx];
            index = [string integerValue];
        }
    }];

    return index;
}
#pragma mark
#pragma mark - 获取已经存储的城市对应的下标
- (NSInteger)getCityIndex{
    
    NSString *city = self.arrInfo[3];
    
    __block NSInteger index = 0;
    [self.model.cities enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isEqualToString:city]) {
            NSString *string = [NSString stringWithFormat:@"%lu",idx];
            index = [string integerValue];
        }
    }];

    return index;
}



- (void)dealloc{
    
    NSLog(@"用户资料修改页面销毁");
}

@end


















